// 云函数入口文件
const cloud = require('wx-server-sdk')
// 初始化 cloud
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
    const db = cloud.database()
    //查询科目总数

    const itemCount = await db.collection('exam_item')
        .where({
            openId: event.userInfo.openId,
        }).count().then(res => {
            return res.total
        })

    if (itemCount >= 12) {
        return {
            code: "500",
            message: "科目最多可以添加12个"
        }
    }
    let result = []
    let data = {
        openId: event.userInfo.openId,
        appId: event.userInfo.appId,
    }
    if (event.type == 'init' && itemCount == 0) {
        data.name = "语文"
        data.time = new Date().getTime()
        console.log("添加科目开始参数为", data)
        await db.collection('exam_item').add({
            data: data,
        }).then(res => {
            console.log("添加科目返回[res]", res)
            res.name = data.name
            result.push(res)
        })

        data.name = "数学"
        data.time = new Date().getTime()
        console.log("添加科目开始参数为", data)
        await db.collection('exam_item').add({
            data: data,
        }).then(res => {
            console.log("添加科目返回[res]", res)
            res.name = data.name
            result.push(res)
        })

        data.name = "英语"
        data.time = new Date().getTime()
        console.log("添加科目开始参数为", data)
        await db.collection('exam_item').add({
            data: data,
        }).then(res => {
            console.log("添加科目返回[res]", res)
            res.name = data.name
            result.push(res)
        })

        data.name = "体育"
        data.time = new Date().getTime()
        console.log("添加科目开始参数为", data)
        await db.collection('exam_item').add({
            data: data,
        }).then(res => {
            console.log("添加科目返回[res]", res)
            res.name = data.name
            result.push(res)
        })


    } else {
        if(!event.name){
            return {
                code: "500",
                message: "科目不能为空"
            }
        }
        data.name = event.name
        data.time = new Date().getTime()
        console.log("添加科目开始参数为", data)
        await db.collection('exam_item').add({
            data: data,
        }).then(res => {
            console.log("添加科目返回[res]", res)
            res.name = data.name
            result.push(res)
        })
    }


    return {
        code: "200",
        data: result,
    }
}

